// const websiteUrl = 'https://api.victory357.com/'; // 测试环境
const websiteUrl = 'https://api.game188.co/'; // 正式环境
import useI18n from '@/store/useI18n.js'
const {
	t
} = useI18n()

// 获取游戏分类和其他信息
const getV2page = (data, header) => post("/index/index/getV2Page", data, header);

// 通过游戏ID获取游戏列表
const getGameList = (data, header) => post("/index/shop/getGameList", data, header);

// 登录
const login = (data, header) => post("/index/user/login", data, header);
// 注册
const register = (data, header) => post("/index/user/register", data, header);
// 系统配置
const getConfigByGroup = (data, header) => post("/index/index/getConfigByGroup", data, header);

// 充值页面初始化数据
const rechargeInit = (data, header) => post("/index/account/recharge_init", data, header);

// 获取转盘配置和数据
const turntablesInit = (data, header) => post("/index/turntables/init", data, header);

// 转盘抽奖
const turntablesBegin = (data, header) => post("/index/turntables/begin", data, header);

// 提现页面初始化数据
const withdrawIinit = (data, header) => post("/index/account/withdraw_init", data, header);

// 提交充值
const recharge = (data, header) => post("/index/account/recharge", data, header);

// 提现
const withdraw = (data, header) => post("/index/account/withdraw", data, header);

// 签到
const checkin = (data, header) => post("/index/user/checkin", data, header);

// vip信息
const vip = (data, header) => post("/index/user/vip", data, header);

// 领取优惠券奖励
const getCouponBonus = (data, header) => post("/index/user/getCouponBonus", data, header);

// 获取个人信息
const getMinLoginUser = (data, header) => post("/index/user/getMinLoginUser", data, header);

// 添加银行卡
const cardAdd = (data, header) => post("/index/account/card_add", data, header);

// 资金明细
const balanceDetails = (data, header) => post("/index/account/balance_details", data, header);

// 邀请页面-代理
const invite = (data, header) => post("/index/user/invite", data, header);;

// 邀请页面-我的数据
const inviteDetails = (data, header) => post("/index/user/invite_details", data, header);

// 修改登录密码
const changepwd = (data, header) => post("/index/user/changepwd", data, header);

// 修改提现密码
const changesecpwd = (data, header) => post("/index/user/changesecpwd", data, header);

// 免费老虎机活动初始化数据
const slotInit = (data, header) => post("/index/user/slot_init", data, header);

// 免费老虎机抽奖
const slotBegin = (data, header) => post("/index/user/slotBegin", data, header);

// 获取游戏链接
const gameUrl = (data, header) => post("/index/shop/game_url", data, header);

// 获取累充活动
const totalRecharge = (data, header) => post("/index/event/total_recharge", data, header);

// 领取累充奖励
const getBonus = (data, header) => post("/index/event/getBonus", data, header);

// 纸牌游戏初始化数据
const cardGameInit = (data, header) => post("/index/user/card_game_init", data, header);

// 纸牌游戏抽奖
const cardGameBegin = (data, header) => post("/index/user/cardGameBegin", data, header);

// 抓娃娃初始化数据
const clawMachineInit = (data, header) => post("/index/user/claw_machine_init", data, header);

// 抓娃娃好友助力
const ClawBegin = (data, header) => post("/index/user/ClawBegin", data, header);

// 领取抓娃娃机奖励
const getClawMachineBonus = (data, header) => post("/index/user/getClawMachineBonus", data, header);

// 理财产品初始化数据（购买卡牌奖励）
const savingInit = (data, header) => post("/index/user/saving_init", data, header);

// 购买理财产品
const savingBuy = (data, header) => post("/index/user/savingBuy", data, header);

// 领取兑换码礼包
const getGift = (data, header) => post("/index/user/getGift", data, header);

// 救济金页面数据（VOLTAR）
const reliefInit = (data, header) => post("/index/user/relief_init", data, header);

// 金钱雨初始化数据
const redenvelopeInit = (data, header) => post("/index/user/redenvelope_init", data, header);

// 领取金钱雨奖励
const settlement = (data, header) => post("/index/user/redEnvelopeBegin", data, header);


// 宝箱猎人初始化数据接口
const rechargeTreasureInit = (data, header) => post("/index/user/recharge_treasure_init", data, header);

// 签到页面初始化数据
const checkinInit = (data, header) => post("/index/user/checkin_init", data, header);

// 点击开启宝箱
const openTreasure = (data, header) => post("/index/user/openTreasure", data, header);

// 领取奖励
const getGoldBonus = (data, header) => post("/index/user/getGoldBonus", data, header);

// 领取宝箱奖励
const getCheckinRechargeBonus = (data, header) => post("/index/user/getCheckinRechargeBonus", data, header);

// 排行榜接口
const ranking = (data, header) => post("/index/user/ranking", data, header);

// 充值回调接口
const rechargeStatus = (data, header) => post("/index/account/rechargeStatus", data, header);

// 快手事件上报
const viewReport = (data, header) => post("/index/index/viewReport", data, header);

const post = async (url, data, header2) => {
	var data = Object.assign({}, data)
	var ht = {
		'Content-Type': 'application/json',
	}
	if (getApp().globalData.userInfo && getApp().globalData.userInfo.token) {
		ht.token = getApp().globalData.userInfo.token
	}
	var header = Object.assign(ht, header2)
	try {
		const res = await uni.request({
			url: websiteUrl + url,
			data: data,
			header: header,
			method: 'POST',
		})
		return res
	} catch (e) {
		return e
	}
}
const roibest_appid = '4445825428'

// 用来做注册通知和首充通知的
const sendRoibestEvent = async (event_name, extra) => {
	const link_id = JSON.parse(
		localStorage.getItem(`__rb_${roibest_appid}_link_id`)
	)
	if (!link_id) {
		return {
			err: 1,
			msg: "no Link_id"
		}
	}
	let data = {
		link_id: link_id,
		event_name: event_name,
		extra: extra
	}
	try {
		const res = await uni.request({
			url: 'https://sdk-report.bttzs.com/report/fb/event',
			data: data,
			header: {
				'content-type': 'application/json',
				Accept: 'application/json'
			},
			method: 'POST',
		})
		res.err = 0
		return res
	} catch (e) {
		e.err = 1
		return e
	}

}

let st = "";

const Purchase = () => {
	if (st != "") {
		clearTimeout(st)
	}
	st = setTimeout(function() {
		recz();
	}, 1000)
}

const recz = () => {
	rechargeStatus({
		orderid: getApp().globalData.orderid
	}).then(res => {
		if (res.data.data && res.data.data.status == '1') {
			// 充值成功
			clearTimeout(st)
			// 判断首充
			// console.log("累计充值：" + Number(getApp().globalData.userInfo.user.recharge_all));
			// console.log(Number(getApp().globalData.userInfo.user.recharge_all) == 0);
			if (Number(getApp().globalData.userInfo.user.recharge_all) == 0) {
				// 发送首充通知
				// sendRoibestEvent('Purchase', {
				// 	is_upgrade_version: 1,
				// 	currency: 'BRL',
				// 	value: getApp().globalData.money
				// }).then(res => {
				// 	console.log(res);
				// })
			}
			// 更新用户信息
			reuserinfo();
		} else {
			st = setTimeout(function() {
				recz();
			}, 1000)
		}
	})
}
// 更新用户信息
const reuserinfo = () => {
	getMinLoginUser({}, {
		"token": getApp().globalData.userInfo.token
	}).then(res => {
		getApp().globalData.userInfo.user = res.data.user
	})
}


const getDate = async (url, data, fun) => {
	try {
		const res = await uni.request({
			url: websiteUrl + url,
			data: data,
			method: 'POST',
		})
		if (fun) {
			fun(res)
		}
	} catch (e) {

	}
}


const getLastWeekRange = () => {
	const today = new Date();
	const dayOfWeek = today.getDay(); // 当前星期几（0-6，0是周日）

	// 计算到上周日的天数差（如果今天是周日，则减0天）
	const daysToLastSunday = dayOfWeek === 0 ? 7 : dayOfWeek;
	const lastSunday = new Date(today);
	lastSunday.setDate(today.getDate() - daysToLastSunday);

	// 上周一 = 上周日 - 6天
	const lastMonday = new Date(lastSunday);
	lastMonday.setDate(lastSunday.getDate() - 6);

	// 格式化日期为 YYYY-MM-DD（可选）
	const format = date => date.toISOString().split('T')[0];

	return {
		firstDay: lastMonday, // 上周一对象
		lastDay: lastSunday, // 上周日对象
		firstDayStr: format(lastMonday), // 格式化字符串
		lastDayStr: format(lastSunday)
	};
}
// 初始化菜单名称
const updateTabBarTexts = () => {

	const tabMap = {
		0: 'menu1',
		1: 'menu2',
		2: 'menu3',
		3: 'menu4',
		4: 'menu5'
	}
	Object.entries(tabMap).forEach(([index, key]) => {
		uni.setTabBarItem({
			index: parseInt(index),
			text: t(key)
		})
	})
}

const bl = data => {
	if (Number(data) < 10) {
		return "0" + data
	} else {
		return data
	}
}

const getRemainingTimeToday = () => {
	const now = new Date();
	const endOfDay = new Date();
	endOfDay.setHours(23, 59, 59, 999); // 设置为当天最后一秒

	const diff = endOfDay - now; // 剩余毫秒数

	// 转换为小时、分钟、秒
	const hours = Math.floor(diff / (1000 * 60 * 60)).toString().padStart(2, '0');
	const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
	const seconds = Math.floor((diff % (1000 * 60)) / 1000).toString().padStart(2, '0');

	return `${hours}:${minutes}:${seconds}`;
}

const getRemainingTimeThisWeek = () => {
	const now = new Date();
	const endOfWeek = new Date();

	// 计算本周日（周日 23:59:59）
	endOfWeek.setDate(now.getDate() + (6 - now.getDay())); // 假设周日是每周的最后一天
	endOfWeek.setHours(23, 59, 59, 999);

	const diff = endOfWeek - now; // 剩余毫秒数

	// 转换为小时、分钟、秒
	const hours = Math.floor(diff / (1000 * 60 * 60)).toString().padStart(2, '0');
	const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
	const seconds = Math.floor((diff % (1000 * 60)) / 1000).toString().padStart(2, '0');

	return `${hours}:${minutes}:${seconds}`;
}

export default {
	roibest_appid,
	reuserinfo,
	Purchase,
	sendRoibestEvent,
	rechargeStatus,
	getLastWeekRange,
	bl,
	websiteUrl,
	getDate,
	updateTabBarTexts,
	getV2page,
	getGameList,
	getConfigByGroup,
	register,
	login,
	rechargeInit,
	turntablesInit,
	turntablesBegin,
	recharge,
	withdraw,
	checkin,
	vip,
	getCouponBonus,
	getMinLoginUser,
	cardAdd,
	balanceDetails,
	invite,
	inviteDetails,
	changepwd,
	changesecpwd,
	slotInit,
	slotBegin,
	withdrawIinit,
	gameUrl,
	totalRecharge,
	getBonus,
	cardGameInit,
	cardGameBegin,
	clawMachineInit,
	ClawBegin,
	getClawMachineBonus,
	savingInit,
	savingBuy,
	getGift,
	reliefInit,
	redenvelopeInit,
	settlement,
	checkinInit,
	rechargeTreasureInit,
	openTreasure,
	getGoldBonus,
	getCheckinRechargeBonus,
	ranking,
	getRemainingTimeToday,
	getRemainingTimeThisWeek,
	viewReport
}